package com.jf.yytgd.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.codec.binary.Base64;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-02-24
 * Time:9:34
 */
public class JwtUtil {
    private static final String SIGNATURE = "kaixi*_jf";
    public static String generateToken(Map<String, String> payload) {
        JWTCreator.Builder builder = JWT.create();
        for (Map.Entry<String, String> entry : payload.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }
        builder.withExpiresAt(newExpiration());
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }
    public static void verifyToken(String token) {
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
    public static Map<String, Object> getPayload(String token) {
        String codedPayload = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token).getPayload();
        String payload = analysisPayload(codedPayload);
        return ObjectUtil.parseJson(payload);
    }
    private static String analysisPayload(String payload) {
        return new String(Base64.decodeBase64(payload));
    }
    public static String updateExpiration(String token) {
        Map<String, Object> payload = getPayload(token);
        payload.remove("exp");
        JWTCreator.Builder builder = JWT.create();
        builder.withPayload(payload).withExpiresAt(newExpiration());
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }
    public static Instant newExpiration() {
        LocalDateTime time = LocalDateTime.now();
        time = time.plusDays(7);
        return time.toInstant(java.time.ZoneOffset.of("+8"));
    }
}
